import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/q_banner.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/values/urls.dart';

class TopBanner extends StatefulWidget {
  @override
  _TopBannerState createState() => _TopBannerState();
}

class _TopBannerState extends State<TopBanner> {
  List<QBanner> _items = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    final placeholder = Container(color: Colors.grey[200]);
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          if (_items.isEmpty) {
            return placeholder;
          }
          return CachedNetworkImage(
            imageUrl: Urls.BASE_URL + _items[index].path,
            placeholder: (c, url) => placeholder,
            fit: BoxFit.cover,
          );
        },
        itemCount: _items.isEmpty ? 1 : _items.length,
        pagination: SwiperPagination(),
        onTap: (i) {
          if (_items.isNotEmpty) {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (c) => WebPage(url: _items[i].link)));
          }
        },
      ),
    );
  }

  void _fetchData() async {
    var data = await XHttp.postJson(Urls.BANNER, {'authStatus': '0'});
    if (data != null && mounted) {
      ListResponse response = ListResponse.fromJson(data);
      if (response.code == 1) {
        setState(() {
          _items.clear();
          _items = response.data.map((e) => QBanner.fromJson(e)).toList();
        });
      }
    }
  }
}
